package com.hamster.crmpre.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hamster.crmpre.config.LoginInterceptor;
import com.hamster.crmpre.mapper.*;
import com.hamster.crmpre.pojo.*;
import com.hamster.crmpre.service.FranchiseProjectsService;
import com.hamster.crmpre.service.MessageQueryService;
import com.hamster.crmpre.service.PhoneUserService;
import com.hamster.crmpre.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import java.util.*;

/**
 * @author ：Lizhipeng
 * @date ：Created in 2019/12/31 10:57
 * @description：加盟项目实现
 * @modified By：
 * @version:
 */
@Service
public class FranchiseProjectsServiceImpl implements FranchiseProjectsService {

    @Autowired
    private AffiliatesProgramConfigMapper affiliatesProgramConfigMapper;
    @Autowired
    private ProjectAllianceMapper projectAllianceMapper;
    @Autowired
    private MessageAllianceMapper messageAllianceMapper;
    @Autowired
    private PersonalMessageMapper personalMessageMapper;
    @Autowired
    private EmployeePerformanceMapper employeePerformanceMapper;
    @Autowired
    private CompanyAccountMapper companyAccountMapper;
    @Autowired
    private PersonalMoneyMapper personalMoneyMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private PhoneUserService phoneUserService;
    @Autowired
    private MessageQueryService messageQueryService;
    /**
     * 获取加盟项目
     * @return
     */
    @Override
    public List<AffiliatesProgramConfig> get() {
        //获取当前登录用户所属部门
        String department = LoginInterceptor.getLoginUser().getDepartment();
        department = department.split(",")[0];
        //获取queryWrapper
        QueryWrapper<AffiliatesProgramConfig> queryWrapper = new QueryWrapper<>();
        //创建返回的对象名
        List<AffiliatesProgramConfig> affiliatesProgramConfigs;
        queryWrapper.eq("del","0");
        //判断当前用户应该获取哪种项目【  0 普通项目加盟 1服务部项目加盟|】
        if (department.equals("2")) {
            //加入判断
            queryWrapper.eq("department", "1");
            affiliatesProgramConfigs = affiliatesProgramConfigMapper.selectList(queryWrapper);
        } else {
            //加入判断
            queryWrapper.ne("department","0");
            affiliatesProgramConfigs = affiliatesProgramConfigMapper.selectList(queryWrapper);
        }

        return affiliatesProgramConfigs;
    }

    /**
     * 插入一条点击确定后的实体
     * @param projectAlliance
     */
        @Override
        public void insert(ProjectAlliance projectAlliance) {
            projectAlliance.setState("0");//项目加盟状态 0未审批 1已同意 2已拒绝
            Customer customer = customerMapper.selectById(projectAlliance.getCustomerId());
            projectAlliance.setCustomerName(customer.getName());//客户姓名
            String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
            projectAlliance.setInputUser(userName);
            projectAlliance.setInputTime(new Date());
            projectAlliance.setDel("0");
            projectAllianceMapper.insert(projectAlliance);
    }

    /**
     * 项目加盟消息的创建
     * @param projectAlliance
     */
    @Override
    @Transactional
    public void messageAdd(ProjectAlliance projectAlliance) {
        //获取当前登录者id和姓名
        String userId = LoginInterceptor.getLoginUser().getUserId();
        String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
//        String userName = LoginInterceptor.getLoginUser().getName();
        //创建项目加盟详情消息对象
        MessageAlliance messageAlliance = new MessageAlliance();
        //解析传来的对象存成可传递的json字符串
        String phone = projectAlliance.getPhone();
        String name = projectAlliance.getEmployeeName();
        String title = projectAlliance.getTitle();
        Double money = projectAlliance.getMoney();
        Map<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        map.put("name",name);
        map.put("title",title);
        map.put("money",money);
        String serialize = JsonUtils.serialize(map);//任务内容字符串
        //设置任务内容
        messageAlliance.setContent(serialize);
        //获得并设置提成,单位元
        Double profit = projectAlliance.getProfit();
        Double profitMoney = profit*money;
        messageAlliance.setMoney(profitMoney);
        //设置数据状态
        messageAlliance.setState("0");
        messageAlliance.setProjectAllianceId(projectAlliance.getId());
        //数据库中添加
        messageAllianceMapper.insert(messageAlliance);

        //创建个人消息中心的消息
        PersonalMessage personalMessage = new PersonalMessage();
        personalMessage.setReceiverId("财务部");
        personalMessage.setReceiverName("财务部");
        personalMessage.setMessageType("项目加盟");
        personalMessage.setSenderId(userId);
        personalMessage.setSenderName(userName);

        //拿出数据库自动生成的id作为个人消息中心messageLink
        personalMessage.setMessageLink(messageAlliance.getId());
        personalMessage.setState("0");
        personalMessage.setCreateTime(new Date());
        personalMessage.setInputUser(userId);
        personalMessage.setDel("0");

        //录入数据库
        personalMessageMapper.insert(personalMessage);


    }

    /**
     * 【这里 项目加盟的提成，记录在个人流水账，没有记录在员工业绩表】
     * 项目加盟处理 【增添一条员工业绩信息、在总账中增添一条信息】
     * @param select 选择情况  1同意 0拒绝
     * @param id 消息中心的id
     */
    @Override
    @Transactional
    public void alliancePass(String select, String id) {
        messageQueryService.setRead(id);//标记消息已读
        //根据消息中心的id，查询MessageLink
        String messageLink = personalMessageMapper.selectById(id).getMessageLink();

        //根据id查到详细信息页面对象
        MessageAlliance messageAlliance = messageAllianceMapper.selectById(messageLink);
        //获取项目加盟的对象
        ProjectAlliance projectAlliance = projectAllianceMapper.selectById(messageAlliance.getProjectAllianceId());
        //获取加盟该项目的客户 对象
        Customer customer = customerMapper.selectById(projectAlliance.getCustomerId());
        //根据选择情况执行相应操作
        if (select.equals("1")) {
            //存入 个人流水账 表
            PersonalMoney personalMoney = new PersonalMoney();
            personalMoney.setTitle("项目加盟提成");
            personalMoney.setCreateTime(new Date());
            personalMoney.setContent("提成："+messageAlliance.getMoney()+"加盟客户："+customer.getName());
            personalMoney.setType("1");//0 客户[分公司、合伙人]   1 员工
            personalMoney.setPersonId(id);//个人id【流水账主人】
            personalMoney.setMoney(messageAlliance.getMoney());
            personalMoneyMapper.insert(personalMoney);

            //改变消息的状态并且添加审批人
            messageAlliance.setState("1");
            messageAlliance.setAuditorId(LoginInterceptor.getLoginUser().getUserId());
            String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
            messageAlliance.setAuditorName(userName);
            //改变项目加盟的状态
            projectAlliance.setState("1");


            //增加一条总账,先获取
            CompanyAccount companyAccount = new CompanyAccount();
            companyAccount.setCreateTime(new Date());
            //明细大标题
            companyAccount.setTitle("项目加盟");
            //明细内容
            String companyAccountContent = projectAlliance.getCustomerId()+","+projectAlliance.getTitle()+","+projectAlliance.getMoney();
            companyAccount.setContent(companyAccountContent);
            //金额
            companyAccount.setMoney(projectAlliance.getMoney());
            //数据库中增添一条总账
            companyAccountMapper.insert(companyAccount);
        } else {
            //改变消息状态并增加审批人信息
            messageAlliance.setState("2");
            messageAlliance.setAuditorId(LoginInterceptor.getLoginUser().getUserId());
            String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
            messageAlliance.setAuditorName(userName);
            //改变项目加盟的状态
            projectAlliance.setState("2");
        }
        //改变数据库
        messageAllianceMapper.updateById(messageAlliance);
        projectAllianceMapper.updateById(projectAlliance);

    }

    /**
     * 分栏 获取项目加盟 列表
     * @return
     */
    @Override
    public List<Map<String,Object>>  listAffiliatesProgram(String name) {
        List<Map<String,Object>> result = new ArrayList<>();
        QueryWrapper<ProjectAlliance> projectAllianceQueryWrapper = new QueryWrapper<>();
        projectAllianceQueryWrapper.eq("state","1");//已同意
        projectAllianceQueryWrapper.eq("employee_id",LoginInterceptor.getLoginUser().getUserId());//项目负责人为当前登录人
        if (StringUtils.isNotBlank(name)){
            projectAllianceQueryWrapper.like("customer_name","%"+name+"%");
        }
        projectAllianceQueryWrapper.orderByDesc("id");
        List<ProjectAlliance> projectAlliances = projectAllianceMapper.selectList(projectAllianceQueryWrapper);

        for (ProjectAlliance projectAlliance : projectAlliances) {
            Map<String,Object> map =new HashMap<>();
            String customerId = projectAlliance.getCustomerId();
            Customer customer = customerMapper.selectById(customerId);
            //TODO 【这里写的很难受，我自己都受不了了】
            map.put("name",customer.getName());//姓名
            map.put("phone",customer.getPhone());//手机
            map.put("wx",customer.getWxNumber());//微信
            map.put("position",customer.getPosition());//职位
            map.put("region",customer.getRegion());//所在地区
            map.put("project",customer.getProjectTitle());//购买项目
            map.put("ProjectAlliance",projectAlliance.getTitle());//加盟项目
            map.put("profit",projectAlliance.getProfit());//提成
            map.put("money",projectAlliance.getMoney());//缴纳金额
            map.put("employeeName",projectAlliance.getEmployeeName());//项目负责姓名
            map.put("contract",projectAlliance.getContract());//是否签订合同  0未签订  1已签订
            result.add(map);
        }
        return result;
    }
}
